package gqz.avdemo.player;

import android.util.Log;
import android.view.Surface;
import android.view.SurfaceView;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Description
 *
 * @author gqz
 * @date 2020/12/21
 */
public class SocketLive {
   private final String TAG = "SocketLive-->";

   WsClient ws;
   Codec codec;

   private class WsClient extends WebSocketClient {

      public WsClient(URI serverUri) {
         super(serverUri);
      }

      @Override
      public void onOpen(ServerHandshake handshakedata) {
         Log.v(TAG, "onOpen: ");
      }

      @Override
      public void onMessage(String message) {
      }

      @Override
      public void onMessage(ByteBuffer bytes) {
         Log.i(TAG, "onMessage(bytes): ");
         byte[] data = new byte[bytes.remaining()];
         bytes.get(data);
         codec.startDecode(data);
      }

      @Override
      public void onClose(int code, String reason, boolean remote) {
         Log.w(TAG, "onClose: ");
      }

      @Override
      public void onError(Exception ex) {
         Log.e(TAG, "onError: ");
      }
   }

   public SocketLive(Surface surface) {
      try {
         codec = new Codec(surface);
         ws = new WsClient(new URI("ws://10.248.6.243:10002"));
         ws.connect();
      } catch (URISyntaxException e) {
         e.printStackTrace();
         onDestroy();
      }
   }

   public void onDestroy() {
      codec.onDestroy();
      if (ws != null) {
         ws.close();
      }
   }
}
